package com.tianji.promotion.util;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Service
public class MyLockFactory {

    @Autowired
    private RedissonClient client;

    private Map<MyLockType, Function<String, RLock>> map = new HashMap<>(){
        {
            put(MyLockType.RE_ENTRANT_LOCK, (name)->client.getLock(name));
            put(MyLockType.FAIR_LOCK, (name)->client.getFairLock(name));
            put(MyLockType.READ_LOCK, (name)->client.getReadWriteLock(name).readLock());
            put(MyLockType.WRITE_LOCK,  (name)->client.getReadWriteLock(name).writeLock());
        }
    };

    /**
     * 只有一个方法的匿名内部类可以用lambda表达式来替代，
     * 一个入参一个返回：Function
     * 一个入参没有返回：Consumer
     * 没有入参一个返回：Supplier
     * */
    public interface AA{
        public RLock getLock(String name);
    }
    private Map<MyLockType, AA> map2 = new HashMap<>(){
        {
            put(MyLockType.RE_ENTRANT_LOCK, new AA(){
                @Override
                public RLock getLock(String name) {
                    return client.getLock(name);
                }
            });
            put(MyLockType.FAIR_LOCK, new AA(){
                @Override
                public RLock getLock(String name) {
                    return client.getFairLock(name);
                }
            });
            put(MyLockType.READ_LOCK, new AA(){
                @Override
                public RLock getLock(String name) {
                    return client.getReadWriteLock(name).readLock();
                }
            });
            put(MyLockType.WRITE_LOCK,  new AA(){

                @Override
                public RLock getLock(String name) {
                    return client.getReadWriteLock(name).writeLock();
                }
            });
        }
    };


    public RLock getLock(MyLockType myLockType, String name){
        return map.get(myLockType).apply(name);
    }

}
